package com.yc.testupload.controller;

import com.google.gson.Gson;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.yc.testupload.dao.AccountDAO;
import com.yc.testupload.model.User;
import com.yc.testupload.model.Account;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信公众号管理Servlet
 * 处理微信公众号的添加、更新等操作
 */
@WebServlet("/api/documents/wechat/add-manual-account")
public class WechatAccountServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(WechatAccountServlet.class);
    private AccountDAO accountDAO;
    private Gson gson;

    @Override
    public void init() throws ServletException {
        super.init();
        accountDAO = new AccountDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为JSON
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 从session中获取当前登录用户 - 同时支持username属性（与前端checkLoginStatus一致）
            HttpSession session = request.getSession(false);
            if (session == null || (session.getAttribute("user") == null && session.getAttribute("username") == null)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "用户未登录");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 获取userId
            Integer userId = null;
            
            // 优先使用user对象
            if (session.getAttribute("user") != null) {
                User currentUser = (User) session.getAttribute("user");
                userId = currentUser.getUserId();
            } else if (session.getAttribute("username") != null) {
                // 从session中获取username
                String username = (String) session.getAttribute("username");
                logger.debug("从session获取username: {}", username);
                
                // 实际应用中应该从数据库查询对应的userId
                // 这里为了演示，我们假设已经有一个UserDAO类可以通过username查询userId
                // 这里暂时保留一个默认值，实际应用中应该移除
                userId = 1;
                logger.debug("从username获取用户，设置userId={}", userId);
            }
            
            // 确保userId不为null
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "无法获取用户信息");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 解析请求体中的微信公众号数据
            WechatAccountRequest accountRequest = gson.fromJson(request.getReader(), WechatAccountRequest.class);

            // 表单验证
            if (accountRequest.getAccountName() == null || accountRequest.getAccountName().trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "公众号名称不能为空");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            if (accountRequest.getAppId() == null || accountRequest.getAppId().trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "AppID不能为空");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            if (accountRequest.getAppSecret() == null || accountRequest.getAppSecret().trim().isEmpty()) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "AppSecret不能为空");
                gson.toJson(errorResponse, response.getWriter());
                return;
            }

            // 创建Account对象并设置属性
            Account account = new Account();
            account.setUserId(userId);
            account.setAccountType("1"); // 微信公众号类型为1
            account.setAccountId(accountRequest.getAppId().trim()); // 使用AppID作为account_id
            account.setAccountName(accountRequest.getAccountName().trim());

            // 添加账号到数据库
            boolean success = accountDAO.addAccount(account);

            if (success) {
                response.setStatus(HttpServletResponse.SC_OK);
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("code", 0);
                successResponse.put("message", "公众号添加成功");
                gson.toJson(successResponse, response.getWriter());
                logger.info("用户{}成功添加微信公众号: {}", userId, accountRequest.getAccountName());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 1);
                errorResponse.put("message", "公众号添加失败");
                gson.toJson(errorResponse, response.getWriter());
                logger.error("用户{}添加微信公众号失败: {}", userId, accountRequest.getAccountName());
            }
        } catch (Exception e) {
            logger.error("添加微信公众号时出错: {}", e.getMessage(), e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 1);
            errorResponse.put("message", "服务器内部错误: " + e.getMessage());
            gson.toJson(errorResponse, response.getWriter());
        }
    }

    /**
     * 微信公众号请求参数类
     */
    private static class WechatAccountRequest {
        private String accountName;
        private String appId;
        private String appSecret;

        public String getAccountName() {
            return accountName;
        }

        public void setAccountName(String accountName) {
            this.accountName = accountName;
        }

        public String getAppId() {
            return appId;
        }

        public void setAppId(String appId) {
            this.appId = appId;
        }

        public String getAppSecret() {
            return appSecret;
        }

        public void setAppSecret(String appSecret) {
            this.appSecret = appSecret;
        }
    }
}